<template>
  <!-- v-pagePermissions="pagePermissions"  -->
  <div class="commonBoxmp">
    <div class="aic h100">
      <deptTree 
      style="margin-right: 10px"
      @updateDept="handleNodeClick"></deptTree>
         <TableV2
        :apiFunction="listUser"
  
        :isInit="false"
        :filter="{
          ...queryParams
        }"
        ref="tableV2Ref"
        :columns="state.columnData"
      >
            <template #tableHeader>
        <div class="jcb aic w100">
          <el-button type="primary" @click="handleAddUser">添加用户</el-button>
        </div>
      </template>
        <template #operation>
          <el-table-column
            label="操作"
            fixed="right"
            width="160px"
            align="left"
          >
            <template #default="scope">
              <div class="aic">
    <el-link type="primary" @click="handleUpdate(scope.row)"
                >修改</el-link
              >
              <el-link type="primary" class="mx5" @click="handleDelete(scope.row)"
                >删除</el-link
              >
              <el-dropdown @command="handleMoreTool($event, scope.row)">
                <el-link class="ml10" type="primary">
                  更多
                  <el-icon class="el-icon--right"> <arrow-down /> </el-icon
                ></el-link>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="updatePwd"
                      >更换密码</el-dropdown-item
                    >
                    <el-dropdown-item command="updaterole"
                      >分配角色</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              </div>
          
            </template>
          </el-table-column>
        </template>
      </TableV2>
     
    </div>
  
    <AllRight v-model="centerDialogVisible" :id="userId" />
    <addOrEdit v-model="drawerEditAdd" :id="userId" @update="getList"/>
  </div>
</template>

<script setup lang="tsx">
import {
  ref,
  reactive,
  getCurrentInstance,
  onMounted,
  toRaw,
  unref,
  nextTick,
  shallowRef,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import deptTree from "/@/views/system/user/component/deptTree.vue";
import formatTool from "/@ts/hooks/format";
import DictTag from "/@/components/DictTag/index.vue";
import AllRight from './component/AllRight.vue'
import addOrEdit from './component/addOrEdit.vue'
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect,
} from "/@ts/axios/urlApi/system/user";
import { getConfigKey } from "/@ts/axios/urlApi/system/config";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { routerPush } from "/@ts/hooks/route";
const router = useRouter();
const route = useRoute();
const { parseTime, addDateRange, getDict } = formatTool();
let dict: any = reactive({
  sys_job_status: [],
});
onMounted(async () => {
  dict.sys_job_status = await getDict("sys_job_status");
});
const ruleFormRef = ref<FormInstance>();
const centerDialogVisible = shallowRef(false);
const userId = shallowRef("")
const drawerEditAdd= shallowRef(false)
const handleGoDetail = (row) => {
  userId.value = row.userId 
  centerDialogVisible.value = true;
};
const state: any = reactive({
  initPassword: "",
  height: 0,
  deptOptions: [],
  form: {},
  // 表单校验
  rules: {
    userName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    nickName: [
      { required: true, message: "用户昵称不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "用户密码不能为空", trigger: "blur" },
      {
        min: 5,
        max: 20,
        message: "用户密码长度必须介于 5 和 20 之间",
        trigger: "blur",
      },
    ],
    email: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    phonenumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
  dateRange: [],
  postOptions: [],
  roleOptions: [],
  tableData: [],
  userVisible: false,
  columnData: [
    {
      label: "用户名称",
      prop: "userName",
      render: ({ row }: any) => {
        return (
          <el-link type="primary" onClick={() => handleGoDetail(row)}>
            {row.userName}
          </el-link>
        );
      },
      visible: true,
        filter:{
        flterType:"input",
      },
    },
    {
      label: "用户昵称",
      prop: "nickName",
      visible: true,
         filter:{
        flterType:"input",
      },
    },
    {
      label: "部门",
      prop: "dept.deptName",
      visible: true,
    },

    {
      label: "手机号",
      prop: "phonenumber",
      visible: true,
    },
    //  <el-switch
    //                   active-value="0"
    //                   inactive-value="1"
    //                   onChange={()=>handleStatusChange(row)}
    //                   modelValue={row.status}
    //                 >
    //                 </el-switch>
    {
      label: "状态",
      prop: "status",
      visible: true,
      render: ({ row }: any) => {
        return (
          <DictTag
            values={row.status}
            dataType="primary"
            options={dict.sys_job_status}
            onClick={() => handleStatusChange(row)}
          ></DictTag>
        );
      },
    },
    {
      label: "创建时间",
      prop: "createTime",
      visible: true,
    },
  ],
  operation: {
    label: "操作",
    prop: "操作",
    width: "180",
    fixed: "right",
    visible: true,
    render: ({ row }: any) => {
      return (
        <div>
          <el-button type="primary" size="small">
            编辑
          </el-button>
          <el-button type="danger" size="small">
            删除
          </el-button>
        </div>
      );
    },
  },
  loading: false,
});
 
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  deptId: undefined,
});
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  const params = unref(queryParams);
  tableV2Ref.value.getList(params);
};
//切换部门数据
const handleNodeClick = (data: any) => {
  queryParams.deptId = data.id;
  handleQuery();
};
// 用户状态修改
const handleAddUser = () => {
  userId.value = ""
  drawerEditAdd.value = true;
  // getUser().then((response: any) => {
  //   state.form = {
  //     sex: "1",
  //   };
  //   state.userVisible = true;
  //   state.title = "添加用户";
  //   state.postOptions = response.posts;
  //   state.roleOptions = response.roles;
  //   state.form.password = state.initPassword;
  //   state.userVisible = true;
  // });
};
const tableV2Ref = ref();
const handleStatusChange = (row: any) => {
  let text = row.status === "0" ? "启用" : "停用";

  ElMessageBox.confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
    .then(function () {
      const data = {
        userId: row.userId,
        status: row.status,
      };
      return changeUserStatus(data);
    })
    .then(() => {
      ElMessage.success(text + "成功");
      tableV2Ref.value.getList();
    })
    .catch(function () {
      // row.status = row.status === "0" ? "1" : "0";
    });
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate();
  if (state.form.userId != undefined) {
    updateUser(state.form).then((response: ResponseConfig) => {
      ElMessage.success("修改成功");
      state.userVisible = false;
      getList();
    });
  } else {
    addUser(state.form).then((response: ResponseConfig) => {
      ElMessage.success("新增成功");
      state.userVisible = false;
      getList();
    });
  }
};
const handleDelete = (row: any) => {
  const userIds = row.userId;
  ElMessageBox.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
    .then(function () {
      return delUser(userIds);
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    })
    .catch(function () {});
};
/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  userId.value = String(row.userId);
 nextTick(()=>{
  drawerEditAdd.value = true;
 })
  // getUser(userId).then((response: ResponseConfig) => {
  //   state.title = "修改用户";
  //   Object.assign(state.form, response.data)
  //   state.postOptions = response.posts;
  //   state.roleOptions = response.roles;
  //   state.form.password = "";
  //   state.userVisible = true;
  // });
};
const updatePwd = (row: any) => {
  ElMessageBox.prompt("请输入新的密码", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(({ value }) => {
      resetUserPwd({
        userId: row.userId,
        password: row.value,
      }).then((res: any) => {
        ElMessage({
          type: "success",
          message: `更新成功`,
        });
        getList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Input canceled",
      });
    });
};
//更多操作
const handleMoreTool = (val: string, row: any) => {
  switch (val) {
    case "updatePwd":
      updatePwd(row);
      break;

    case "updaterole":
      handleAuthUser(row);
      break;
  }
};
const handleAuthUser = (row: any) => {
  const userId = row.userId;
  routerPush("/system/user-auth/role/" + userId);
};
//查询用户列表
const getList = () => {
  // state.loading = true;
  // queryParams.pageNum = pageInfo.currentPage;
  // queryParams.pageSize = pageInfo.pageSize;
  // listUser(addDateRange(queryParams, state.dateRange)).then((response: any) => {
  //   state.tableData = response.rows;
  //   pageInfo.total = response.total;
  //   state.loading = false;
  // });
  tableV2Ref.value.getList()
};
/** 查询部门下拉树结构 */
const getDeptTree = () => {
  deptTreeSelect().then((response: ResponseConfig) => {
    state.deptOptions = response.data;
  });
};

onMounted(() => {
  getConfigKey("sys.user.initPassword").then((response: ResponseConfig) => {
    state.initPassword = response.msg;
  });
  getList();
  getDeptTree();
});
</script>

<style scoped lang="scss"></style>
